"""
用户相关 Schemas
"""
from pydantic import BaseModel, Field
from typing import Optional, List
from datetime import datetime


class UserStats(BaseModel):
    """用户统计数据"""
    monthlyBookings: int = 0
    totalMatches: int = 0
    totalSpent: float = 0.0
    favoriteVenue: Optional[str] = None


class UserBase(BaseModel):
    """用户基础信息"""
    nickName: str = Field(..., min_length=1, max_length=100)
    avatar: Optional[str] = None
    phone: Optional[str] = None
    positions: List[str] = []
    cityId: Optional[str] = None
    cityName: Optional[str] = None


class UserCreate(UserBase):
    """创建用户"""
    password: Optional[str] = Field(None, min_length=6)
    wechatOpenid: Optional[str] = None


class UserUpdate(BaseModel):
    """更新用户信息"""
    nickName: Optional[str] = Field(None, min_length=1, max_length=100)
    avatar: Optional[str] = None
    phone: Optional[str] = None
    positions: Optional[List[str]] = None
    cityId: Optional[str] = None
    cityName: Optional[str] = None


class UserResponse(BaseModel):
    """用户响应"""
    id: str
    nickName: str
    avatar: Optional[str] = None
    phone: Optional[str] = None
    positions: Optional[List[str]] = None
    cityId: Optional[str] = None
    cityName: Optional[str] = None
    rating: float = 0.0
    teamIds: Optional[List[str]] = None
    role: Optional[str] = "user"
    createdAt: Optional[datetime] = None
    stats: Optional[UserStats] = None
    
    class Config:
        from_attributes = True
        populate_by_name = True
        
    @classmethod
    def from_orm(cls, obj):
        """从 ORM 对象创建"""
        # 构建统计数据
        stats = UserStats(
            monthlyBookings=obj.monthly_bookings or 0,
            totalMatches=obj.total_matches or 0,
            totalSpent=obj.total_spent or 0.0,
            favoriteVenue=obj.favorite_venue
        )
        
        # 处理 positions
        positions = obj.positions if obj.positions else []
        
        # 处理 team_ids
        team_ids = obj.team_ids if obj.team_ids else []
        
        return cls(
            id=obj.id,
            nickName=obj.nick_name,
            avatar=obj.avatar,
            phone=obj.phone,
            positions=positions,
            cityId=obj.city_id,
            cityName=obj.city_name,
            rating=obj.rating or 0.0,
            teamIds=team_ids,
            role=obj.role if hasattr(obj, 'role') else "user",
            createdAt=obj.created_at,
            stats=stats
        )


class UserLogin(BaseModel):
    """用户登录"""
    phone: Optional[str] = None
    password: Optional[str] = None
    wechatCode: Optional[str] = None  # 微信登录code


class LoginResponse(BaseModel):
    """登录响应"""
    token: str
    userInfo: UserResponse

